﻿#include "menuservice.h"

#include <databasecenter.h>
#include <menudao.h>
#include <QtDebug>

MenuService::MenuService(QObject *parent) : QObject(parent)
{
    db = DatabaseCenter::getInstance().getConnection();
}

MenuService::~MenuService()
{
    DatabaseCenter::getInstance().releaseConnection(db);
}

bool MenuService::getMenuVOListByPid(QList<MenuVO> &list, uint64_t pid)
{
    bool res = false;
    MenuDao objectDao(db);
    QList<Menu> menuList;
    if (objectDao.getListByPid(menuList,pid))
    {
        res = true;
        for(Menu &menuTmp:menuList){
            MenuVO menuVO;
            menuVO.fromMenu(menuTmp);
            QList<MenuVO> children;
            getMenuVOListByPid(children,menuTmp.getId());
            menuVO.setChildren(children);
            list.append(menuVO);
        }
    }
    return res;
}

//判断是否存在交集
bool hasCommonElements(const QStringList &list1, const QStringList &list2) {
    for (const QString &item:list1) {
        if (list2.contains(item)) {
            return true;
        }
    }
    return false;
}

bool MenuService::getMenuVoListByPermissionsAndPid(QList<MenuVO> &list, QStringList permissions, uint64_t pid)
{
    bool res = false;
    MenuDao objectDao(db);
    QList<Menu> menuList;
    if (objectDao.getListByPid(menuList,pid))
    {
        res = true;
        for(Menu &menuTmp:menuList){
            MenuVO menuVO;
            menuVO.fromMenu(menuTmp);
            QList<MenuVO> children;
            if(getMenuVoListByPermissionsAndPid(children,permissions,menuTmp.getId())){
                menuVO.setChildren(children);
            }
            //权限判断
            if(permissions.contains(QString::number(menuVO.getId()))){
                list.append(menuVO);
            }
            //不判断权限
//            list.append(menuVO);
        }
    }
    return res;
}


bool MenuService::getMenuVoListByPermissions(QList<MenuVO> &list, QList<QString> permissions)
{
    return getMenuVoListByPermissionsAndPid(list,permissions,0);
}

bool MenuService::getMenuVoList(QList<MenuVO> &list)
{
    return getMenuVOListByPid(list,0);
}

bool MenuService::getList(QList<Menu> &list)
{
    MenuDao objectDao(db);
    return objectDao.getList(list);
}

bool MenuService::getOne(Menu &object)
{
    MenuDao objectDao(db);
    return objectDao.getOne(object);
}

bool MenuService::saveOne(Menu &object)
{
    MenuDao objectDao(db);
    return objectDao.saveOne(object);
}

bool MenuService::deleteOne(Menu &object)
{
    MenuDao objectDao(db);
    return objectDao.deleteOne(object);
}
